﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SAPbouiCOM;

namespace BoAddonBiz_FreightForwarder.Custom
{
    public abstract class B1Form_CustomsDeclaration : SAPBoAddon.B1Form
    {
        #region abstract
        protected abstract string MasterTable { get; }
        protected abstract string SubTable { get; }
        protected abstract string InOut { get; }
        #endregion
        #region override
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {

            #region 控件是否可编辑

            FormSetting.FormModeSetting.itmNewModeDisable = new string[] { "35", "l_base" };

            FormSetting.FormModeSetting.StatusItemUID = "7";
            SAPBoAddon.BrowseModeSetting BrowseModeSetting;
            #region P状态
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "P";
            //P状态下可编辑的状态
            BrowseModeSetting.itmBrowseModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            //P状态下不可编辑的状态
            BrowseModeSetting.itmBrowseModeDisable = new string[] { "3", "35", "l_base", "cmb_tt", "29", "111", "113", "123", "125" };
            #endregion
            #region R,C,D
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "R";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "C";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "D";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            #endregion
            FormSetting.FormModeSetting.itmFindModeEnable = new string[] { "3" };
            #endregion
            FormSetting.AutoGetObjectNextNumber = true;

            FormSetting.MatrixSetting.MtxUID = "mtx_0";
            FormSetting.MatrixSetting.MenuAddNewLine = true;
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.NotAllowNoLineSave = true;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_12";
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = true;
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "VisOrder";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = SubTable;
            FormSetting.MatrixSetting.Add();
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("57"), "DocCurrCod", "CurrName", "OCRN", "DocCurrCod", null, null, true);//币种
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("75"), "Code", "Name", "@AVA_FF_OTRM", "Code", null, null, true);//贸易方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("77"), "Code", "Name", "@AVA_FF_BAMD", "Code", null, null, true);//成交方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("69"), "Code", "Name", "@AVA_FF_PAMD", "Code", null, null, true);//交税方式
            //Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("877"), "Code", "Name", "@AVA_FF_OSUC", "Code", null, null, true);//监管方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("879"), "Code", "Name", "@AVA_FF_QTRT", "Code", null, null, true);//检疫要求
            //Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("877_1"), "Code", "Name", "@AVA_FF_OSUC", "Code", null, null, true);//监管方式2
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("885"), "Code", "Name", "@AVA_FF_OSTM", "Code", null, null, true);//结汇方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("109"), "Code", "Name", "@Package", "Code", null, null, true);//包装类型
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("885"), "Code", "Name", "@AVA_FF_OSTM", "Code", null, null, true);//结汇方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("t22"), "Code", "Name", "@ModesOfTransport", "Code", null, null, true);//运输方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("t24"), "Code", "Name", "@Property", "Code", null, null, true);//征免性质
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("t2"), "Code", "Name", "@District", "Code", null, null, true);//境内区域

            Utils.InitialMatrixComboBox(SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_20", "Code", "Name", "@AVA_FF_OSUC");//监管方式
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_16", "Code", "Name", "@AVA_FF_OPRI", null, null, null);//单位
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_5", "Code", "Name", "@AVA_FF_OPRI", null, null, null);//单位
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_7", "Code", "Name", "@AVA_FF_OPRI", null, null, null);//单位

            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_17", "Code", "Name", "OCRY", null, null, "ISNULL(U_ForeignName,'') <> ''");//源产地
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_8", "Code", "Name", "@Usage", null, null, null);//用途/生产厂家
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_18", "Code", "Name", "@Property", null, null, null);//征免性质


            if (new Regex(@"\b\d+\b").Match(InitPar.FatherFormUID).Success)
            {
                this.CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetValue(this.CurrentForm, this.CurrentForm.DataBrowser.BrowseBy, InitPar.FatherFormUID);
                this.CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
            #region 加载下拉列表框数据
            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            //根据员工主数据上配置的此人是否是有什么样的类型进行配置 --Vincent.yin
            int UserID = SAPBoAddon.B1Addon.B1Addon.SBOCompany.UserSignature;
            rs.DoQuery(@"SElECT T4.Code
                                                        FROM OUSR T0
	                                                        INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                                        INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                                        INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                                        INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                                        Where  T0.UserID = " + UserID);
            if (rs.RecordCount <= 0)
            {
                Utils.ComboBox_InitialItem(rs, CurrentForm.Items.Item("cmb_tt"), "Code", "Name", "@AVA_FF_OMOT", null, "Where U_Type='Air' or U_Type IS NULL", true, false);//运输方式
            }
            else
            {
                Utils.ComboBox_InitialItem(rs, CurrentForm.Items.Item("cmb_tt"), "T4.Code", "T4.Name", "OUSR", null, string.Format(@" T0
	                                                                                                                                    INNER JOIN OHEM T1 ON T0.UserID = T1.UserID
	                                                                                                                                    INNER JOIN [@AVA_OHEM] T2 ON T1.U_BusinessType = T2.Code
	                                                                                                                                    INNER JOIN [@AVA_HEM1] T3 ON T2.Code = T3.Code
	                                                                                                                                    INNER JOIN [@AVA_FF_OMOT] T4 ON T3.U_BusinessType = T4.Code
                                                                                                                                    Where T0.UserID ={0}                                                                                                                                                                                                                     
                                                                                                                                    ", UserID), true, false);//运输方式
            }
            #endregion
        }
        #endregion
        #region constructor
        public B1Form_CustomsDeclaration()
        {
            this.frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(ChooseFormListEvent);
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(ItemEvent);
            this.frm_FormDataEvent += new SAPBoAddon.IB1FormEvents.B1FormDataEventEventHandler(FormDataEvent);
        }
        #endregion
        #region events
        void FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                #region 添加新的业务单
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_ADD)
                    try
                    {
                        SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                        SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(MasterTable);
                        string SQL = @"
                                Declare @DocEntry int
                                Declare @SerialNum nvarchar(max)
                                SELECT @DocEntry = AutoKey FROM ONNM Where ObjectCode = 'AVA_FF_BusinessOpera'

                                create table #temp (sernum nvarchar(max))
                                insert #temp EXEC AVA_AL_GetSerialNumber N'AVA_FF_BusinessOpera',N'{1}' 
                                select @SerialNum = sernum from #temp
                                drop table #temp

                                Insert Into [@AVA_FF_OBNO] (DocEntry,DocNum,Period,Instance,Series,Handwrtten,Canceled,Object,UserSign,Transfered,Status,CreateDate,CreateTime,DataSource
	                                ,U_DocDate,U_TransportType,U_SerialNum,U_MBLNumber,U_SBLNumber,U_Status,U_CardCode,U_CardName,U_CntctCode,U_IsClearance)
	                                Values
	                                (@DocEntry,@DocEntry,8,0,43,'N','N','AVA_FF_BusinessOpera',{0},'N','O',CONVERT(char(10),getdate(),120),cast(datepart(hh,getdate()) as int)*100 + cast(datepart(mi,getdate()) as int),'I'
	                                ,GETDATE(),'{1}',@SerialNum,'{2}','{3}','P','{4}','{5}','{6}','N')

                                UPDATE ONNM SET AutoKey = @DocEntry + 1 Where ObjectCode = 'AVA_FF_BusinessOpera'
                                ";
                        SQL = string.Format(SQL, SBOCompany.UserSignature.ToString(),
                                            dbds.GetValue("U_TransportType", dbds.Offset),
                                            dbds.GetValue("U_MainBill", dbds.Offset),
                                            dbds.GetValue("U_SplitBill", dbds.Offset),
                                            dbds.GetValue("U_CardCode", dbds.Offset),
                                            dbds.GetValue("U_CardName", dbds.Offset),
                                            dbds.GetValue("U_CntctCode", dbds.Offset));
                        rs.DoQuery(SQL);
                    }
                    catch
                    {
                        BubbleEvent = false;
                    }
                #endregion
            }
        }

        void ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction == false)
            {
                #region pane
                if (pVal.ItemUID == "tab_0" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 1;
                }
                if (pVal.ItemUID == "tab_1" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 2;
                }
                if (pVal.ItemUID == "tab_2" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 3;
                }
                if (pVal.ItemUID == "tab_3" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 5;
                }
                #endregion
                /*计算行总计*/
                if (pVal.ItemUID == "mtx_0" && (pVal.ColUID == "col_14" || pVal.ColUID == "col_15") && pVal.ItemChanged && pVal.Row > 0)
                {
                    Utils.CalcLineTotal(this.CurrentForm, "mtx_0", SubTable, pVal.Row);
                }
                if (pVal.ItemUID == "65" && pVal.ItemChanged)
                {

                    SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "cargo_60", SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, pVal.ItemUID));
                }
                if (pVal.ItemUID == "btn_add" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    if (pVal.FormMode != 3)
                    {
                        SBOApp.Menus.Item(B1MenuTypes.sys_Add).Activate();
                    }
                }
                #region 生成报关文件
                if (pVal.ItemUID == "btn_Xml" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CustomsDeclarationXml cdxml = new CustomsDeclarationXml();
                    string DocEntry = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "3").ToString().Trim();
                    string TaskId = cdxml.CreateXml(DocEntry, InOut);
                    if (string.IsNullOrEmpty(TaskId) == false)
                    {
                        try
                        {
                            SBOApp.SetStatusBarMessage("正在生成报关单据……", BoMessageTime.bmt_Long, false);
                            CustomsResponse checkResponse = new CustomsResponse();
                            checkResponse.CheckResponseFile(TaskId, DocEntry, InOut, CurrentForm.UniqueID);
                        }
                        catch (Exception ex)
                        {
                            throw (ex);
                        }
                    }
                }
                #endregion
                #region 报关数据导入
                if (pVal.ItemUID == "btn_load" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    ImportExcelData.ExcelDataImportSystem(CurrentForm, InOut, "FF");
                }
                #endregion
            }
        }

        void ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                SAPbouiCOM.ChooseFromList cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                SAPbouiCOM.Conditions cons;
                SAPbouiCOM.Condition con;
                switch (pVal.ChooseFromListUID)
                {
                    case "CFL_OCRD":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup13";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "C";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_D":
                    case "CFL_OCRD_C":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup11";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_OR;
                        con = cons.Add();
                        con.Alias = "QryGroup12";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_CB":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "S";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                }
            }
            else
            {
                if (pVal.Action_Success)
                {
                    SAPbouiCOM.Matrix omtx = default(SAPbouiCOM.Matrix);
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(MasterTable);
                    if (pVal.ChooseFromListUID == "CFL_OCRD")//客户
                    {
                        dbds.SetValue("U_CardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CardName", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_CntctCode", dbds.Offset, Cntct.FullName);
                        }
                        //Utils.GetSalesPerson(dbds, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_CB")//报关行
                    {
                        dbds.SetValue("U_CustomsBrokerCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CustomsBrokerName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_CBCntctCode", dbds.Offset, Cntct.FullName);
                            dbds.SetValue("U_CBCntctTel", dbds.Offset, Cntct.Cellolar);
                            dbds.SetValue("U_CBCntctEmail", dbds.Offset, Cntct.Email);
                        }
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_D")//收发货单位
                    {
                        dbds.SetValue("U_DeliverCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_DeliverName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_C")//经营单位
                    {
                        dbds.SetValue("U_CompanyCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CompanyName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dbds.SetValue("U_CusComInsRegCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CusComInsRegCode", 0).ToString());
                        dbds.SetValue("U_CusRegCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CusRegCode", 0).ToString());/*取客户[海关注册编码] 2012-7-16 by WangPeng*/
                    }
                    else if (pVal.ChooseFromListUID == "CFL_PORT")
                    {
                        //之前的全部注释掉，ChooseFormList取值 出口口岸列表 modified by WangPeng 2012-7-6
                        dbds.SetValue("U_PortCode", dbds.Offset, pVal.SelectedObjects.GetValue("Code", 0).ToString());
                        dbds.SetValue("U_Port", dbds.Offset, pVal.SelectedObjects.GetValue("Name", 0).ToString());
                    }
                    //行 商品编码
                    else if (pVal.ChooseFromListUID == "CFL_PdtCode")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(SubTable);
                        omtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item("mtx_0").Specific;
                        dbds.Offset = SAPBoAddon.B1Assistant.DBDataSource.GetMatrixOfOffset(dbds, "col_f", "Lineid");
                        omtx.GetLineData(pVal.Row);
                        dbds.SetValue("U_HSCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_HSCode", 0).ToString());
                        omtx.SetLineData(pVal.Row);
                    }
                }
            }
        }
        #endregion
    }
}
